package com.my.study.design.prototype;

import java.io.*;

/**
 * @author Carlos
 * @version 1.0
 * @Description TODO
 * @date 2021/7/10 23:14
 **/
public class Sheep implements Cloneable, Serializable {
    private static final long serialVersionUID = 3218658029313960642L;

    private String name;
    private int age;
    private String color;
    private Sheep friend;

    public Sheep() {
    }

    public Sheep(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Sheep getFriend() {
        return friend;
    }

    public void setFriend(Sheep friend) {
        this.friend = friend;
    }

    /**
     * 深拷贝
     *
     * @return
     */
    @Override
    protected Object clone(){
        Sheep sheep = null;

        try {
            // 1.完成基本数据类型的拷贝
            sheep = (Sheep) super.clone();
            // 2.完成引用数据类型的拷贝
            sheep.setFriend((Sheep) friend.clone());
        } catch (CloneNotSupportedException e) {
            System.out.println(e.getMessage());
        }
        return sheep;
    }

    /**
     * 深拷贝 - 序列化和反序列
     *
     * @return
     */
    public Object deepCloneBySerializable() {

        Sheep obj = null;
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);

            obj = (Sheep) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                ois.close();
                bis.close();
                oos.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return obj;
    }


    /**
     * 浅拷贝的克隆对象
     *
     * @return
     */
//    @Override
//    protected Object clone() {
//        Sheep sheep = null;
//        try {
//            sheep = (Sheep)super.clone();
//        } catch (CloneNotSupportedException e) {
//            System.out.println(e.getMessage());
//        }
//        return sheep;
//
//    }



    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }
}
